import time
from MicroWebSrv2 import MicroWebSrv2, WebRoute, POST, GET
from time import sleep
from devices import led_controller
import devices
import config
import machine
import utils


@WebRoute(POST, '/', name='Index')
def Index(_, request):
    request.Response.ReturnRedirect('/web/index.html')


@WebRoute(POST, '/set/rgb', name='SetRGB')
def SetRGB(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    led_controller.set_rgb(data['rgb'])
    request.Response.ReturnJSON(200, data)


@WebRoute(POST, '/set/rgb/status', name='SetRGBStatus')
def SetRGBStatus(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    led_controller.switch(data['status'])
    request.Response.ReturnJSON(200, data)


@WebRoute(POST, '/set/wifi', name='SetWIFI')
def SetWIFI(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    config.WIFI_NAME = data['name']
    config.WIFI_PWD = data['pwd']
    config.save_conf()
    request.Response.ReturnJSON(200, data)
    time.sleep(1)
    machine.reset()  # 重启


@WebRoute(POST, '/set/city', name='SetCity')
def SetCity(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    config.WEATHER_LOC = data['loc']
    config.WEATHER_CITY = data['city']
    config.save_conf()
    request.Response.ReturnJSON(200, data)


@WebRoute(POST, '/set/api', name='SetAPI')
def SetCity(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    config.SERVER_API = data['server_api']
    config.SECRET_ID = data['secret_id']
    config.SECRET_KEY = data['secret_key']
    config.save_conf()
    request.Response.ReturnJSON(200, data)


@WebRoute(POST, '/set/birthday/date', name='SetBirthdayDate')
def SetBirthdayDate(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    config.BIRTHDAY_DATE = data['date']
    config.save_conf()
    request.Response.ReturnJSON(200, data)


@WebRoute(POST, '/set/mirror_flip', name='SetMirrorFlip')
def SetMirrorFlip(_, request):
    data = request.GetPostedJSONObject()
    print(data)
    config.MIRROR_FLIP = data['mirror_flip']
    config.save_conf()
    request.Response.ReturnJSON(200, data)
    time.sleep(1)
    machine.reset()  # 重启


@WebRoute(GET, '/system/info', name='SystemInfo')
def GetSystemInfo(_, req):
    req.Response.ReturnJSON(200, utils.get_system_info())


mws2 = MicroWebSrv2()

mws2.SetEmbeddedConfig()
# 静态资源路径
mws2.RootPath = '/web'
# 允许跨域
mws2.AllowAllOrigins = True
mws2.CORSAllowAll = True

if __name__ == '__main__':
    config.load_conf()
    devices.connect_wifi(config.WIFI_NAME, config.WIFI_PWD)
    mws2.StartManaged()
    try:
        while mws2.IsRunning:
            sleep(1)
    except KeyboardInterrupt:
        pass
